package fun.coding.leetcode;

public class MergeTwoSortedLists {

	public static void main(String[] args) {
		// l1: 2->6->8
		// l2: 1->9
		ListNode list1 = new ListNode(2);
		ListNode list1A = new ListNode(6);
		ListNode list1B = new ListNode(8);
		list1.next = list1A;
		list1A.next = list1B;
		
		ListNode list2 = new ListNode(1);
		ListNode list2A = new ListNode(9);
		list2.next = list2A;
		
		MergeTwoSortedLists m = new MergeTwoSortedLists();
		ListNode head = m.mergeTwoLists(list1, list2);
		
		LeetCodeHelpers.printList(head);
		
	}
	
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		ListNode dummyHead = new ListNode(-1);
		ListNode cur = dummyHead;
		
		while (l1 != null && l2 != null) {
			if (l1.val < l2.val) {
				cur.next = l1;
				l1 = l1.next;
			} else {
				cur.next = l2;
				l2 = l2.next;
			}
			cur = cur.next;
		}
		
		if (l1 != null) {
			cur.next = l1;
		}
		
		if (l2 != null) {
			cur.next = l2;
		}
		
		return dummyHead.next;
	}
	
	// Of course, This avoids creating extra ListNodes, creating new nodes are silly
	// Using a dummy node will make this code much simpler
	public ListNode mergeTwoListsOld(ListNode l1, ListNode l2) {
		ListNode head = null;
		ListNode it = null;
		
		while (l1 != null && l2 != null) {
			if (l1.val < l2.val) {
				if (head == null) {
					head = l1;
				}
				
				if (it == null) {
					it = l1;
				} else {
					it.next = l1;
					it = l1;
				}
				
				l1 = l1.next;
			} else {
				if (head == null) {
					head = l2;
				}
				
				if (it == null) {
					it = l2;
				} else {
					it.next = l2;
					it = l2;
				}
				l2 = l2.next;
			}
		}
		
		if (l1 != null) {
			if (it == null) {
				it = l1;
				head = it;
			} else {
				it.next = l1;
				it = l1;
			}
		}
		
		if (l2 != null) {
			if (it == null) {
				it = l2;
				head = it;
			} else {
				it.next = l2;
				it = l2;
			}
		}
		
		return head;
    }
}
